package com.github.catvod.spider;

import android.annotation.SuppressLint;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Util;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 酱视频发布页: https://jtv8868.pro/
 */
public class JiangVideo extends Spider {
    private String siteUrl="https://ers3.dy55922.pro:5268/v2/";

    // 首页数据接口
    private String homeUrl = siteUrl+"home/index/a.jsn";

    private String categoryUrl=siteUrl+"category";
    private String detailUrl=siteUrl+"videoplay";

    private String searchUrl = siteUrl+"home/search";

    // 搜索页关键接口
    private String searchHomeUrl = siteUrl+"home/searchhome";


    // 获取从请求头
    private Map<String, String> getHeader() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.APP_CHROME);
        header.put("sec-ch-ua-platform", "\"Android\"");
        return header;
    }

    @Override
    public String homeContent(boolean filter) throws Exception {
        String result = OkHttp.string(homeUrl, getHeader());
        String searchKey = OkHttp.string(searchHomeUrl, getHeader());
        JSONObject result_json = new JSONObject(result);
        JSONArray category_arr = result_json.getJSONArray("category");
        List<Class> classes=new ArrayList<>();
        classes.add(new Class("#", "首页"));
        for (int i = 0; i < category_arr.length(); i++) {
            JSONObject category_obj = category_arr.getJSONObject(i);
            String category_name = category_obj.getString("name");
            String cid = category_obj.getString("cid");
            classes.add(new Class(cid, category_name));
        }
        JSONObject searchHome_result = new JSONObject(searchKey);
        JSONArray hot_keyword = searchHome_result.getJSONArray("hot_keyword");
        JSONArray guess_keyword = searchHome_result.getJSONArray("guess_keyword");
        for (int i = 0; i < hot_keyword.length(); i++) {
            String keyword = hot_keyword.getString(i);
            classes.add(new Class("search_"+keyword, keyword));
        }
        for (int i = 0; i < guess_keyword.length(); i++) {
            String keyword = guess_keyword.getString(i);
            classes.add(new Class("search_"+keyword, keyword));
        }
        // 进行获取今日最新
        List<Vod> vods = new ArrayList<>();
        JSONArray today_new = result_json.getJSONArray("today_new");
        processJsonArray(today_new, vods);
        return Result.string(classes, vods);
    }

    /**
     * 将秒数转换为 HH:MM:SS 格式
     *
     * @param seconds 输入的秒数
     * @return 转换后的字符串格式
     */
    @SuppressLint("DefaultLocale")
    public static String convertSecondsToHMS(double seconds) {
        int totalSeconds = (int) Math.floor(seconds); // 取整数部分
        int hours = totalSeconds / 3600;
        int remainingSeconds = totalSeconds % 3600;
        int minutes = remainingSeconds / 60;
        int finalSeconds = remainingSeconds % 60;

        return String.format("%02d:%02d:%02d", hours, minutes, finalSeconds);
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        List<Vod> vods = new ArrayList<>();

        // 关键字搜索页分类
        if (tid.startsWith("search_")) {
            String keyword = tid.substring(7);
            HashMap<String, String> params = new HashMap<>();
            params.put("keyword", keyword);
            params.put("page", pg);
            params.put("limit", "20");
            String result = OkHttp.string(searchUrl, params, getHeader());
            JSONObject result_json = new JSONObject(result);
            String currentPage = result_json.getString("current_page");
            String total = result_json.getString("total");
            String last_page = result_json.getString("last_page");
            JSONArray vod_list = result_json.getJSONArray("data");
            processJsonArray(vod_list, vods);
            return Result.string(Integer.parseInt(currentPage), Integer.parseInt(last_page), 20, Integer.parseInt(total), vods);
        }
        if (tid.equals("#")) {
            // 首页
            String result = OkHttp.string(homeUrl, getHeader());
            JSONObject result_json = new JSONObject(result);

            // 处理 today_new 数据
            processJsonArray(result_json.getJSONArray("today_new"), vods);

            // 处理 hot_list 数据
            processJsonArray(result_json.getJSONArray("hot_list"), vods);

            // 处理 home_list 数据
            JSONArray page_list = result_json.getJSONArray("home_list");
            for (int i = 0; i < page_list.length(); i++) {
                JSONArray videoList = page_list.getJSONObject(i).getJSONArray("videoList");
                processJsonArray(videoList, vods);
            }

            return Result.string(vods);
        }
        // 分类页面
        HashMap<String, String> params = new HashMap<>();
        params.put("category_child_id", "");
        params.put("category_id", tid);
        params.put("limit", "20");
        params.put("page", pg);
        String category_result = OkHttp.string(categoryUrl, params, getHeader());
        JSONObject category_result_json = new JSONObject(category_result).getJSONObject("data");
        String total = category_result_json.getString("total");
        String last_page = category_result_json.getString("last_page");
        // 处理分类数据的 vodList
        processJsonArray(category_result_json.getJSONArray("data"), vods);

        return Result.string(Integer.parseInt(pg), Integer.parseInt(last_page), 20, Integer.parseInt(total), vods);
    }

    /**
     * 通用方法：处理 JSONArray 并创建 Vod 对象
     *
     * @param jsonArray JSONArray 数据
     * @param vods      Vod 对象列表
     */
    private void processJsonArray(JSONArray jsonArray, List<Vod> vods) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String id = jsonObject.getString("id");
            String title = jsonObject.getString("title");
            String img = jsonObject.getString("url");
            String duration = convertSecondsToHMS(jsonObject.getDouble("duration"));
            vods.add(new Vod(id, title, img, duration));
        }
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        params.put("vid", ids.get(0));
        String detail_result = OkHttp.string(detailUrl, params, getHeader());
        JSONObject detail_result_json = new JSONObject(detail_result).getJSONObject("video");
        String title = detail_result_json.getString("title");
        String img = detail_result_json.getString("url");
        String duration = convertSecondsToHMS(detail_result_json.getDouble("duration"));
        String play_url =  detail_result_json.getString("self_cdn_path");
        Vod vod = new Vod();
        vod.setVodPlayUrl("播放$"+play_url);
        vod.setVodPic(img);
        vod.setVodName(title);
        vod.setVodPlayFrom("m3u8");
        vod.setVodRemarks(duration);
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        return Result.get().url(id).parse().header(getHeader()).string();
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        params.put("keyword", key);
        params.put("page", "1");
        params.put("limit", "20");
        String search_result = OkHttp.string(searchUrl, params, getHeader());
        System.out.println("search_result"+search_result);
        JSONArray result_arr = new JSONObject(search_result).getJSONArray("data");
        List<Vod> vods = new ArrayList<>();
        processJsonArray(result_arr, vods);
        return Result.string(vods);
    }
}
